package de.baumann.browser.present

import de.baumann.browser.base.BasePresenter
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.ICreateWalletView
import de.baumann.browser.utils.web3j.ETHWalletUtils
import de.baumann.browser.utils.web3j.WalletDaoUtils
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.util.concurrent.TimeUnit


class CreateWalletPresenter : BasePresenter<ICreateWalletView>() {
    fun createWallet() {
        Observable.create(ObservableOnSubscribe<ETHWallet> { emitter ->
            try {
                val ethWallet = ETHWalletUtils.generateMnemonic(view!!.getWalletName(), view!!.getWalletPwd())
                emitter.onNext(ethWallet);
            } catch (e: Exception) {
                emitter.onError(e)
            }
        }).throttleFirst(3, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<ETHWallet> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: ETHWallet) {
                        if (view != null)
                            view?.jumpToWalletBackUp(t)
                    }

                    override fun onError(e: Throwable) {
                        if (view != null)
                            view?.onError(e.message);
                    }

                });
    }
}
